﻿using H.Hands;
using H.Utils;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace H.KML.KeyBoards
{
    /// <summary>
    /// 点击单个按钮的按键任务
    /// </summary>
    public class KMKey : IKeyBoard
    {
        /// <summary>
        /// Hand实例
        /// </summary>
        protected readonly KMHand _Hand;

        /// <summary>
        /// 需要按下的键
        /// </summary>
        private readonly string _Key;

        /// <summary>
        /// 构造一个按键任务
        /// </summary>
        /// <param name="key"></param>
        public KMKey(KMHand hand,string key)
        {
            _Hand = hand;
            _Key = key;
        }


        ///<inheritdoc/>
        public virtual bool Click()
        {
            if (Down())
            {
                try
                {
                    DelayUtil.Delay(100, 120);//最快速地按两下键盘也得100ms的时间,故取100~120ms延时
                    return Up();
                }
                catch (ThreadInterruptedException)
                {
                    return false;
                }
                finally
                {
                    Up();
                }
            }
            else
            {
                return false;
            }
        }

        ///<inheritdoc/>
        public bool Down()
        {
            return _Hand._KM.KeyDown(_Key) == 1;
        }

        ///<inheritdoc/>
        public bool Up()
        {
            return _Hand._KM.KeyUp(_Key) == 1;
        }
    }
}
